// pages/news/submit.js
const util = require('../../utils/util.js');
const apiUrl = require('../../utils/apiUrl.js');
var http = require('../../utils/httpHelper.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    lgid: 0,
    type: 0,
    articleTitle: "",
    detail: {},
    winWidth: 0,
    winHeight: 0,
    imageList: [],
    coverSrc: '',
    videoSrc: '',
    collectUrl: '',
    showLoading: false,
    readOnly: false,
    keyboardHeight: 0,
    isIOS: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    var id = options.id;
    if (id) {
      that.setData({
        id: id,
      });

      that.loadData();
    }

    var type = options.type;
    if (type) {
      that.setData({
        type: type,
      });
    }

    var title = options.title;
    if (title) {
      wx.setNavigationBarTitle({
        title: title,
      })
    }

    var lgid = options.lgid;
    if (lgid) {
      that.setData({
        lgid: lgid,
      });

      that.loadLGData();
    }

    /**
     * 获取系统信息
     */
    wx.getSystemInfo({

      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });

    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS
    })

    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },
  collectUrlInput: function (e) {
    this.setData({
      collectUrl: e.detail.value
    })
  },
  cjBtnTap: function () {
    var that = this;

    if (that.data.collectUrl.length == 0) {
      wx.showModal({
        title: '请输入采集网址',
      });
      return;
    }
    that.setData({
      loaddinghidden: false,
    });

    var parameter = {};
    parameter['url'] = that.data.collectUrl;

    http.ApiGet(apiUrl.UrlDoCacth, parameter, function (res) {
      var result = res.result;
      if (result.errorCode == 1) {
        that.setData({
          loaddinghidden: true,
          articleTitle: res.data.subject,
        });

        var thumb = res.data.thumb;

        if (thumb.length > 0) {
          that.setData({
            coverSrc: thumb[0]
          });
        }

        that.editorCtx.setContents({
          html: res.data.message,
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          }
        });
      } else {
        wx.showModal({
          title: result.errorMessage
        });
      }
    });
  },
  loadData: function () {
    var that = this;
    var parameter = {};
    parameter['id'] = that.data.id;

    http.ApiGet(apiUrl.UrlNewsDetail, parameter, function (res) {
      if (res.result.errorCode == 1) {

        var detail = res.data;

        that.setData({
          articleTitle: detail.title,
          type: detail.show_type,
          coverSrc: detail.images,
          detail: detail,
        });
        that.onEditorReady();
      } else {
        wx.showModal({
          title: res.result.errorMessage
        });
      }
    });
  },
  loadLGData: function () {
    var that = this;
    var parameter = {};
    parameter['id'] = that.data.lgid;
    http.ApiGet(apiUrl.UrlLaigaoDetail, parameter, function (res) {
      var imageArray = [];

      if (res.thumb.length > 0) {
        imageArray.push(res.thumb);
      }

      that.setData({
        loaddinghidden: true,
        articleTitle: res.title,
        coverSrc: imageArray,
        detail: res,
      });
      console.log("loadLGData");
      that.onEditorReady();

    });
  },
  chooseImage: function () {
    var that = this
    wx.chooseImage({
      count: 9,
      success: function (res) {
        for (let j = 0; j < res.tempFilePaths.length; ++j) {
          that.uploadImage(res.tempFilePaths[j], 0)
        }
      }
    })
  },
  submit: function (e) {
    var that = this;
    var formData = {};
    // console.log(e.detail.value);

    var title = e.detail.value.title;
    if (title == "") {
      wx.showModal({
        title: '请填写标题',
        content: ''
      });
      return;
    }
    formData['title'] = title;

    formData['type'] = that.data.type;

    formData['appId'] = util.APPID;
    
    formData['openId'] = wx.getStorageSync("openId");

    // var user = wx.getStorageSync("user");


    // //图片
    // var image = '';
    // var imgsList = that.data.imageList;
    // if (imgsList.length > 0) {
    //   image = imgsList[0];
    //   if (imgsList.length > 1) {
    //     for (let j = 1; j < imgsList.length; ++j) {
    //       image += "," + imgsList[j];
    //     }
    //   }
    // }
    // formData['images'] = image;
    formData['images'] = [that.data.coverSrc];


    // var videoSrc = that.data.videoSrc;
    // if (videoSrc.length > 0) {
    //   formData['video'] = videoSrc;
    // }
    // console.log(formData);

    that.editorCtx.getContents({
      success: (res) => {
        console.log(res);
        if (res.text.length > 0 && res.html != "<p><br></p>") {

          var content = res.html;

          formData["content"] = content;

          that.submitPost(formData);
        } else {
          wx.showModal({
            title: '请填写内容',
          });
          return;
        }
      },
      fail: (err) => {
        wx.showModal({
          title: '提交失败',
        });
        console.log(err);
      }
    });
  },
  submitPost(formData) {
    var that = this;

    wx.showToast({
      title: '正在提交',
      icon: 'loading',
      duration: 2000,
      mask: true,
    });

    var url = apiUrl.UrlNewsSubmit;

    if (that.data.id > 0) {
      formData["id"] = that.data.id;
    }

    // console.log(formData);
    // return;

    http.ApiPost(url, formData, function (res) {
      if (res.result.errorCode == 1) {
        wx.showToast({
          title: '提交成功！',
          icon: 'success',
          duration: 2000
        });

        if (that.data.type == 1) {
          wx.setStorageSync("refreshList", "news");
        } else {
          wx.setStorageSync("refreshList", "news");
        }

        console.log("刷新列表");
        wx.navigateBack();
      } else {
        wx.showModal({
          title: res.result.errorMessage
        });
      }
    });
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const {
      windowHeight,
      platform
    } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({
      editorHeight,
      keyboardHeight
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context;
      var detail = that.data.detail;
      if (detail.content) {
        that.editorCtx.setContents({
          html: detail.content,
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          }
        });
      }
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)
  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  textIndent() {
    this.editorCtx.format('textIndent', '2em');
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 9,
      success: function (res) {
        for (let j = 0; j < res.tempFilePaths.length; ++j) {
          that.uploadImage(res.tempFilePaths[j], 0)
        }
      }
    })
  },
  uploadImage: function (path, type) {
    var that = this
    that.showLoading();
    var postData = {};
    var token = wx.getStorageSync("token");
    postData["token"] = token;
    wx.uploadFile({
      url: apiUrl.UrlUpload,
      filePath: path,
      name: 'file',
      formData: postData,
      success: function (res) {
        that.cancelLoading();
        var resdata = JSON.parse(res.data);
        var result = resdata.result;
        if (result.errorCode == 1) {
          wx.hideToast();

          var imgUrl = resdata.url;

          //封面图
          if (type == 1) {
            that.setData({
              coverSrc: imgUrl
            })
          } else {
            that.editorCtx.insertImage({
              src: imgUrl,
              width: '100%',
              success: function () {
                console.log('insert image success');
              }
            })
          }

        } else {
          wx.showModal({
            title: result.errorMessage
          });
        }
      },
      fail: function (err) {
        console.log(err);
        that.cancelLoading();
        wx.showModal({
          title: '上传出错！'
        });
      }
    })
  },
  chooseCover: function () {
    var that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        for (let j = 0; j < res.tempFilePaths.length; ++j) {
          that.uploadImage(res.tempFilePaths[j], 1)
        }
      }
    })
  },
  delImg: function () {
    var that = this;
    wx.showModal({
      title: '确定删除？',
      success: function (res) {
        if (res.confirm) {
          that.setData({
            coverSrc: ""
          })
        }
      }
    })

  },
  showLoading: function () {
    this.setData({
      showLoading: true
    })
  },
  cancelLoading: function () {
    this.setData({
      showLoading: false
    })
  },
})